﻿/// <reference path="/Scripts/MicrosoftAjax/MicrosoftAjax.debug.js"/>
/// <reference path="/WebUI/core.debug.js"/>
/// <reference path="/WebUI/DataView/script.debug.js" />

Doo.Validator = function (element) {
    ///<summary>属性有效性验证</summary>
    ///<remarks>这是一个用于表单验证的控件</remarks>
    Doo.Validator.initializeBase(this, [element]);
}
Doo.Validator.prototype = {
    initialize: function () {
        //解析Dom树并生成验证器集合
        this._validators = new Doo.Validator.ValidatorCollection();
    },

    _validators: null, //验证集合

    dispose: function () {
        //Add custom dispose actions here
        Doo.Validator.callBaseMethod(this, 'dispose');
    }
}

Doo.Validator.registerClass('Doo.Validator', Doo.ControlBase);

Doo.Validator.ValidateStatus = function () { }

Doo.Validator.ValidateStatus.prototype = {
    Valid: 0, //通过验证
    InValid: 1, //未通过验证
    Validating: 2, //正在验证[异步]
    Custom: 3//自定义状态
}
Doo.Validator.ValidateStatus.registerEnum("Doo.Validator.ValidateStatus");

Doo.Validator.ValidatorCollection = function () {
    ///<summary>验证器集合</summary>
    this._items = [];
}
Doo.Validator.ValidatorCollection.prototype = {
    _items: null,
    add: function (item) {
        this._items.push(item);
    },
    remove: function (item) {
        Array.remove(this._items, item);
    },
    _validatethreadfunc: function () {
        ///<summary>异步验证管理线程</summary>
        var f = function () { };
        f.prototype = {
            
        };
        return f;
    },
    _validatethread: null,
    validate: function (value, data, callback) {
        ///<summary>对控件容器进行验证</summary>
        ///<param name="value">验证的值</param>
        ///<param name="data">所有属性</param>
        ///<param name="callback">如果存在需要异步验证的情况，则在验证状态变化时调用此callback</param>
        var isvalid = Doo.Validator.ValidateStatus.Valid;
        var msgerr = '';
        var vs = this._items;
        for (var j = 0; j < vs.length; j++) {
            var args = { isvalid: Doo.Validator.ValidateStatus.Valid, icon: null, msg: null }
            vs[j].validate(this.vaelem, args);
            if (args.isvalid == false) {
                isvalid = false;
                this.validate_callback(vs[j], args);
                msgerr = args.msg;
                break;
            }
        }
        return { isvalid: isvalid, msg: msgerr, custom: null };
    }
}
Doo.Validator.ValidatorCollection.registerClass("Doo.Validator.ValidatorCollection");


//以下是各类验证
/* 一个支持客户端和服务器端验证的Ajax控件 *
* 目前已经支持文本输入、单选复选、[RadioButtonList、CheckBoxList]（仅长度验证）等 *
* 支持长度、正则、Web服务、表达式跨控件、自定义客户端及服务器端验证 *
* (C)DuYu 2009 */
if (!window.PControl) PControl = {};
PControl.BaseValidator = function () { };
with (PControl.BaseValidator) {
    prototype.init = function (elem, args) {
        if (args.mserr) this.mserr = args.mserr;
        else this.mserr = null;
    };
    prototype.getdefaulterror = function () { return "未通过验证"; };
};

///Length
PControl.LengthValidator = function (elem, args) {
    this.init(elem, args);
    this._max = args.max ? parseInt(args.max) : null;
    this._min = args.min ? parseInt(args.min) : null;
};
function PControl$LengthValidator$validate(value, vargs) {
    ///提示,vargs:{isvalid:false,icon:null}
    var len = value ? (value.length || 0) : 0;
    if ((this._max && this._max < len) || (this._min && this._min > len)) {
        vargs.isvalid = false;
        return false;
    }
    vargs.isvalid = true;
    return true;
}
PControl.LengthValidator.prototype = new PControl.BaseValidator();
//为了兼容firefox，只得将prototype提到with外面
with (PControl.LengthValidator) {
    prototype.validate = PControl$LengthValidator$validate;
    constructor = PControl.LengthValidator;
    prototype.getdefaulterror = function () { if (this._max < 1) return "长度应不小于" + this._min; else if (this._min < 0) return "长度应小于" + this._max; else return "长度应在" + this._min + "和" + this._max + "之间"; };
}
///Regex
PControl.RegexValidator = function (elem, args) {
    this.init(elem, args);
    this._pattern = args.pattern;
}
function PControl$RegexValidator$validate(value, vargs) {
    if (value.length > 0) {
        //此处放正则验证
        var tmp = new RegExp(this._pattern);
        var succ = tmp.test(value);
        if (!succ) { vargs.isvalid = false; ; return; }
    }
    vargs.isvalid = true;
}
PControl.RegexValidator.prototype = new PControl.BaseValidator();
with (PControl.RegexValidator) {
    prototype.validate = PControl$RegexValidator$validate;
    constructor = PControl.RegexValidator;
}
///Multi
PControl.MultiValidator = function (elem, args) {
    this.init(elem, args);
    this._expression = args.expression;
    if (args.vactls && args.vactls.length > 0) {
        this._vactls = args.vactls;
        var ctls = this._vactls.split(',');
        var va = this;
        for (var i = 0; i < ctls.length; i++) {
            $addHandler($get(ctls[i]), 'blur', function () { va.Validator.validate(va.Validator.vaelem) });
        } //为每个关联控件附加函数
    }
}
function PControl$MultiValidator$validate(elem, vargs) {
    var value = elem.value;
    if (value.length > 0) {
        //多重控件验证
        //1.得到values列表
        var values = [value];
        if (this._vactls) {
            var ctls = this._vactls.split(',');
            for (var i = 0; i < ctls.length; i++) {
                values.push($get(ctls[i]).value);
            }
        }
        //2.定义各类局部变量和函数
        var strlen = this.strlen;
        var intval = this.intval;
        var floatval = this.floatval;
        var dateval = this.dateval;
        var strval = this.strval;
        var evalcodes = [];
        var dzb = ['a', 'b', 'c', 'd'];
        for (var i = 0; i < values.length; i++) {
            evalcodes.push('var $' + dzb[i] + '=values[' + i + '];');
        }
        var evalcode = evalcodes.join('');
        eval(evalcode);
        //3.执行语句以判断是否成功
        var ans = eval(this._expression);
        vargs.isvalid = ans ? true : false;
    }
    else {
        vargs.isvalid = true;
    }
}
PControl.MultiValidator.prototype = new PControl.BaseValidator();
with (PControl.MultiValidator) {
    prototype.validate = PControl$MultiValidator$validate;
    prototype.strlen = function (s) { return s.length; }
    prototype.intval = function (s) { return parseInt(s); }
    prototype.floatval = function (s) { return parseFloat(s); }
    prototype.dateval = function (s) {
        var retVal = Date.parse(s);
        if (!retVal) {
            //按年-月-日解析
            var pattern = /(\d{4})[^\d]?(\d{1,2})[^\d]?(\d{1,2})/;
            var match = pattern.exec(s);
            if (!match || !match.length || match.length < 4) return new Date(1901, 1, 1);
            retVal = new Date(match[1], match[2], match[3]);
            if (retVal) return retVal;
            return new Date(1901, 1, 1);
        }
        return retVal;
    }
    prototype.strval = function (s) { return s.toString(); }
    constructor = PControl.MultiValidator;
}
///Custom
PControl.CustomValidator = function (elem, args) {
    this.init(elem, args);
    this._vafun = args.vafunction;
    if (args.service) this.service = args.service;
    if (args.method) this.method = args.method;
};
function PControl$CustomValidator$validate(elem, vargs) {
    var value = elem.value;

    //检查是否已经验证过...
    if (value == this['lastvalue']) { vargs.isvalid = this['lastresult']; return; }

    var len = value.length;
    if (this._vafun && this._vafun.length > 0 && eval(this._vafun + "(value,elem)") != true) {
        vargs.isvalid = false;
        return;
    }

    if (this.service && this.method) {
        var script = this.service + "." + this.method + "(value,PControl$CustomValidator$validate_h,null,{va:this,value:value});";
        eval(script);
        vargs.isvalid = false;
        vargs.msg = "请稍候，正在检查对错...";
        vargs.icon = "Loading";
        return;
    }

    vargs.isvalid = true;
}
function PControl$CustomValidator$validate_h(result, context) {
    var va = context.va;
    var parent = va.Validator;
    var isvalid = result == "true";

    var args = { isvalid: isvalid, msg: (isvalid || result.length == 0) ? null : result, icon: null };
    va.lastvalue = context.value;
    va.lastresult = isvalid;
    parent.validate_callback(va, args);

}
PControl.CustomValidator.prototype = new PControl.BaseValidator();
with (PControl.CustomValidator) {
    prototype.validate = PControl$CustomValidator$validate;
    constructor = PControl.CustomValidator;
}
